#include "task.h"

int taskInqueue(threadPool_t *pool, char *cmd, int netfd)
{
    taskNode_t *newNode = (taskNode_t *)malloc(sizeof(taskNode_t));
    if (newNode == NULL)
    {
        perror("malloc");
        return -1;
    }
    LOG_INFO("taskInqueue: %s\n", cmd);
    newNode->taskId = netfd;
    strcpy(newNode->taskContent, cmd);
    newNode->next = NULL;
    // 添加到任务队列
    pthread_mutex_lock(&pool->mutex);
    if (pool->taskQueue.head == NULL)
    {
        pool->taskQueue.head = newNode;
        pool->taskQueue.tail = newNode;
    }
    else
    {
        pool->taskQueue.tail->next = newNode;
        pool->taskQueue.tail = newNode;
    }
    pool->taskQueue.taskNum++;
    pthread_cond_signal(&pool->cond);
    pthread_mutex_unlock(&pool->mutex);
    return 0;
}

int taskDequeue(threadPool_t *pool, char *cmd, int *netfd)
{

    pthread_mutex_lock(&pool->mutex);
    if (pool->taskQueue.head == NULL)
    {
        LOG_ERROR("taskDequeue: task queue is empty\n");
        return -1;
    }
    memcpy(cmd, pool->taskQueue.head->taskContent, sizeof(pool->taskQueue.head->taskContent));
    *netfd = pool->taskQueue.head->taskId;
    taskNode_t *temp = pool->taskQueue.head;
    pool->taskQueue.head = pool->taskQueue.head->next;
    pool->taskQueue.taskNum--;
    if (pool->taskQueue.head == NULL)
    {
        pool->taskQueue.tail = NULL;
    }
    free(temp);
    pthread_mutex_unlock(&pool->mutex);
    LOG_INFO("taskDequeue: %s\n", cmd);
    return 0;
}